import { constantRouterMap ,asyncRouterMap } from '@/config/routerConfig'
import { getAllMenus } from '@/api/login'

const permission = {
  state: {
    routers: constantRouterMap, //基础路由
    addRouters: [] //要添加到动态路由中的路由信息
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
	//动态添加路由信息
	GenerateRoutes({commit},menuList){
		return new Promise(resolve =>{
			//1.获取服务端所有菜单信息
			getAllMenus().then(res => {
				const result = res.data.responseData
				const serviceMenuList = {}
				for(let i = 0 ; i < result.length;i++){
					serviceMenuList[result[i].authCode] = result[i]
				}
				const accessedRouters = filterAsyncRouter(asyncRouterMap, menuList, serviceMenuList)
				console.log('路由信息',accessedRouters)
				commit('SET_ROUTERS', accessedRouters)
				resolve(accessedRouters)
			})
		})
	}
  }
}


/**
 * <h1>递归过滤异步路由表，返回符合用户角色权限的路由表</h1>
 * @param {Object} asyncRouterMap  前台所有的菜单即frontMenuList
 * @param {Object} menuList        用户后台所具有的权限,这个是通过authCode进行获取的
 * @param {Object} serviceMenuList 后台所有菜单信息
 */
function filterAsyncRouter(asyncRouterMap, menuList, serviceMenuList){
	const accessedRouters = asyncRouterMap.filter(route =>{
		if(hasPermission(menuList,route)){
			if (!(route.hidden !== undefined && route.hidden === true)) {
				route.name = serviceMenuList[route.authCode].menuName
				route.icon = serviceMenuList[route.authCode].menuIcon
			}
			if (route.children && route.children.length) {
				route.children = filterAsyncRouter(route.children, menuList, serviceMenuList)
			}
			return true
		}
	})
	return accessedRouters
}

/**
 * 通过authCode判断是否与当前用户权限匹配
 * @param {Object} menuList    用户后台所具有的权限,这个是通过authCode进行获取的
 * @param {Object} route
 */
function hasPermission(menuList,route){
	if(route.authCode){
		if(menuList[route.authCode] != undefined){
			return menuList[route.authCode]
		}else{
			if (menuList[route.authCode] === undefined && route.hidden === true) {
				return true
			} else {
				return false
			}
		}
	}else{
		return true
	}
}

export default permission